package com.purong.purong.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.activity.ArticleSearchActivity;
import com.purong.purong.adapter.ViewPagerAdapter;
import com.purong.purong.bean.ArticleCatBean;
import com.purong.purong.bean.ArticleCatListBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.widget.SmoothScrollViewPage;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wenjiezeng on 2017/11/8.
 */
public class ArticleFragment extends BaseFragment {
    private ImageView statusBar;
    private SlidingTabLayout tabLayout;
    private SmoothScrollViewPage mViewPager;
    private ViewPagerAdapter mAdapter;
    private ArrayList<Fragment> fragmentList = new ArrayList<>();
    private ArrayList<String> titleList = new ArrayList<>();
    private int selectPosition=0;//当前fragment位置
    private ArticleCatListBean bean;
    private List<ArticleCatBean> catList=new ArrayList<>();
    public static boolean jumpToCredit;
    private boolean getCatSuc;
    @Override
    public int getRootViewId() {
        return R.layout.fragment_article;
    }

    @Override
    public void initView(View rootView) {
        statusBar = (ImageView) rootView.findViewById(R.id.status_bar);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
            statusBar.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        }else {
            statusBar.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, CommonUtil.getStatusBarHeight(getActivity())));
        }
        rootView.findViewById(R.id.search_lay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), ArticleSearchActivity.class);
                startActivity(intent);
            }
        });
        tabLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_tablayout);
        mViewPager = (SmoothScrollViewPage) rootView.findViewById(R.id.view_pager);

        mAdapter = new ViewPagerAdapter(getChildFragmentManager(), fragmentList);
        mAdapter.setPageTitle(titleList);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setMaxSpace(2);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectPosition=position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.setViewPager(mViewPager);
        tabLayout.setTabSpaceEqual(false);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {

            }

            @Override
            public void onTabReselect(int position) {


            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!getCatSuc){
            getCat();
        }else {
            jumpCredit();
        }

    }
    private void jumpCredit(){
        if (jumpToCredit){
            jumpToCredit=false;
            if (catList==null||catList.size()==0)
                return;
            for (int i = 0; i <catList.size() ; i++) {
                if (catList.get(i).getCategory_name().equals("信用卡")){
                    if (fragmentList.size()>i){
                        mViewPager.setCurrentItem(i);
                    }

                }
            }
        }
    }
    @Override
    public void initData(){
    }
    private void getCat(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        getCatSuc= request(Contant.ARTICLE_CATEGORY, params, true, false);
    }
    private void setCat(){
        fragmentList.clear();
        titleList.clear();
        ArticleListFragment fragment;
        Bundle args;

        for (int i = 0; i <catList.size() ; i++) {
            fragment = new ArticleListFragment();
            args = new Bundle();
            args.putString("CAT_ID",catList.get(i).getCategory_id());
            fragment.setArguments(args);
            fragmentList.add(fragment);
            titleList.add(catList.get(i).getCategory_name());

        }
        mAdapter.notifyDataSetChanged();
        tabLayout.notifyDataSetChanged();

    }
    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.ARTICLE_CATEGORY)){
            if (responseInfo.isRequestOk){
                try{
                    bean= JSON.parseObject(responseInfo.content,ArticleCatListBean.class);
                    if (bean!=null&&bean.getArticle_category_list()!=null){
                        ArticleCatBean hotCat=new ArticleCatBean();
                        hotCat.setCategory_id("-1");
                        hotCat.setCategory_name("精选");
                        hotCat.setCategory_code("JX");
                        catList.add(hotCat);
                        catList.addAll(bean.getArticle_category_list());
                        setCat();
                        getCatSuc=true;
                        jumpCredit();
                    }else {
                        getCatSuc=false;
                    }
                }catch (Exception e){
                    getCatSuc=false;
                }
            }else {
                getCatSuc=false;
            }
        }
    }

    public void scroll2Top(){
        if (fragmentList!=null&&fragmentList.size()>=selectPosition+1){
            ((ArticleListFragment)fragmentList.get(selectPosition)).scroll2Top();
        }
    }
    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mViewPager.setCurrentItem(msg.what);
        }
    };
}
